package user;

import java2021_9_23.DButil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    //主要实现一个根据用户名找密码这样的逻辑即可
    //此处我们期望用户名是唯一的,查询到的结果只有一条或者0条,所以在建表的时候应该给用户名一个unique约束
    public User selectName(String name){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            //1.与数据库建立连接
            connection = DButil.getConnection();
            //2.构造sql
            String sql = "select*from user where userName = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,name);
            //3.执行sql
            resultSet = statement.executeQuery();
            if(resultSet.next()){
                //用户存在,返回一个具体的User对象
                //需要根据当前User是否是管理员,决定返回一个Admin还是NormalUser
               boolean isAdmin = resultSet.getInt("isAdmin") == 1;
               User user = null;
               if(isAdmin){
                   user = new Admin();
               }else{
                   user = new NormalUser();
               }
               user.setUserId(resultSet.getInt("userId"));
               user.setUserName(resultSet.getString("userName"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }else{
                //不存在此用户
                return null;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DButil.close(connection,statement,resultSet);
        }
        //抛异常了,也返回null
        return null;
    }
}
